<template>
  <div class="delivery-staff-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.username"
        placeholder="用户名"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-input
        v-model="listQuery.phone"
        placeholder="手机号"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate">
        添加
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="加载中..."
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column label="ID" width="80" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="用户名" min-width="120" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.username }}</span>
        </template>
      </el-table-column>

      <el-table-column label="真实姓名" min-width="120" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.realName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="邮箱" min-width="180" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.email }}</span>
        </template>
      </el-table-column>

      <el-table-column label="手机号" min-width="130" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.phone }}</span>
        </template>
      </el-table-column>

      <el-table-column label="状态" min-width="100" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" min-width="180" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" min-width="180" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="handleUpdate(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </div>

    <!-- 送水员表单对话框 -->
    <el-dialog :title="dialogStatus === 'create' ? '添加送水员' : '编辑送水员'" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :model="temp" :rules="rules" label-width="100px" style="width: 400px; margin: 0 auto;">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="temp.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogStatus === 'create'">
          <el-input v-model="temp.password" type="password" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="temp.realName" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="temp.email" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="temp.phone" />
        </el-form-item>
        <el-form-item label="状态" prop="status" v-if="dialogStatus === 'update'">
          <el-select v-model="temp.status" placeholder="请选择状态">
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDeliveryStaffList, addDeliveryStaff, updateDeliveryStaff, deleteDeliveryStaff } from '@/api/admin'
import { validUsername, validPassword, validPhone, validEmail } from '@/utils/validate'

export default {
  name: 'DeliveryStaff',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('用户名不能少于3个字符'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (!validPassword(value)) {
        callback(new Error('密码不能少于6个字符'))
      } else {
        callback()
      }
    }
    const validatePhone = (rule, value, callback) => {
      if (!validPhone(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }
    const validateEmail = (rule, value, callback) => {
      if (!validEmail(value)) {
        callback(new Error('请输入正确的邮箱'))
      } else {
        callback()
      }
    }
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        username: undefined,
        phone: undefined
      },
      temp: {
        id: undefined,
        username: '',
        password: '',
        phone: '',
        status: 1,
        realName: '',
        email: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      rules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
        email: [{ required: true, trigger: 'blur', validator: validateEmail }],
        phone: [{ required: true, trigger: 'blur', validator: validatePhone }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      
      // 构建查询参数
      const params = {
        current: this.listQuery.page,
        size: this.listQuery.limit,
        keyword: this.listQuery.username || this.listQuery.phone // 使用username或phone作为关键字
      }
      
      // 添加调试日志
      console.log('查询送水员参数:', params)
      
      getDeliveryStaffList(params).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      }).catch(error => {
        console.error('获取送水员列表失败:', error)
        this.listLoading = false
        this.$message({
          message: '获取送水员列表失败',
          type: 'error',
          duration: 2000
        })
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        username: '',
        password: '',
        phone: '',
        status: 1,
        realName: '',
        email: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          // 不需要在这里设置role，API函数会处理
          
          addDeliveryStaff(tempData).then(response => {
            if (response.code === 200) {
              this.dialogFormVisible = false
              this.$message({
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            } else {
              this.$message({
                message: response.message || '创建失败',
                type: 'error',
                duration: 2000
              })
            }
          }).catch(error => {
            console.error('添加送水员失败:', error)
            this.$message({
              message: '添加送水员失败',
              type: 'error',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // 复制一份，避免直接修改原数据
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          // 确保保留role字段
          tempData.role = 'DELIVERY'
          
          updateDeliveryStaff(tempData).then(response => {
            if (response.code === 200) {
              this.dialogFormVisible = false
              this.$message({
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            } else {
              this.$message({
                message: response.message || '更新失败',
                type: 'error',
                duration: 2000
              })
            }
          }).catch(error => {
            console.error('更新送水员失败:', error)
            this.$message({
              message: '更新送水员失败',
              type: 'error',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确认删除该送水员吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDeliveryStaff(row.id).then(response => {
          if (response.code === 200) {
            this.$message({
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          } else {
            this.$message({
              message: response.message || '删除失败',
              type: 'error',
              duration: 2000
            })
          }
        }).catch(error => {
          console.error('删除送水员失败:', error)
          this.$message({
            message: '删除送水员失败',
            type: 'error',
            duration: 2000
          })
        })
      }).catch(() => {})
    }
  },
  beforeRouteEnter(to, from, next) {
    const userRole = localStorage.getItem('userRole')
    if ((userRole || '').toLowerCase() !== 'admin') {
      next('/404')
    } else {
      next()
    }
  }
}
</script>

<style scoped>
.delivery-staff-container {
  padding: 30px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.filter-container {
  display: flex;
  align-items: center;
  margin-bottom: 25px;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.filter-item {
  margin-right: 15px;
}

.pagination-container {
  margin-top: 25px;
  text-align: center;
  background-color: #fff;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  table-layout: fixed;
}

.el-table__body {
  width: 100% !important;
}

.el-button--primary {
  background-color: #409EFF;
  border-color: #409EFF;
  padding: 10px 20px;
}

.el-button--success {
  background-color: #67C23A;
  border-color: #67C23A;
  padding: 10px 20px;
}

.el-button--danger {
  background-color: #F56C6C;
  border-color: #F56C6C;
}

.add-button {
  margin-left: auto;
}

.el-input {
  width: 220px;
}

.el-tag {
  padding: 5px 10px;
}

.el-dialog__body {
  padding: 20px 30px;
}

.el-form-item {
  margin-bottom: 22px;
}

.dialog-footer {
  text-align: right;
  margin-top: 10px;
}
</style> 